package com.baichuan.zntx.handler;

import com.baichuan.zntx.domain.BaseMessage;
import com.baichuan.zntx.domain.MessageEnum;
import com.baichuan.zntx.domain.DataMessage;
import com.baichuan.zntx.service.IMessageHandlerService;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

@Slf4j
@RequiredArgsConstructor
public class ServerListenerHandler extends SimpleChannelInboundHandler<BaseMessage> {
    private final IMessageHandlerService messageHandlerService;
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        super.handlerAdded(ctx);
        log.info("有新的连接：[{}]", ctx.channel().id().asLongText());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, BaseMessage message) throws Exception {
        //对不同消息进行处理
        messageHandlerService.processMessage(channelHandlerContext, message);
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        super.handlerRemoved(ctx);
        log.info("设备下线了：[{}]", ctx.channel().id().asLongText());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // 打印异常
        log.info("异常：{}", cause.getMessage());
        // 关闭连接
        ctx.close();
    }
}
